package com.huidao.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.huidao.dao.GoodsDao;
import com.huidao.dao.GoodsDaoImpl;
import com.huidao.dao.OrderDao;
import com.huidao.dao.OrderDaoImpl;
import com.huidao.dao.ShopDao;
import com.huidao.dao.ShopDaoImpl;
import com.huidao.entity.Order;
import com.huidao.entity.Shoppingcart;
import com.huidao.entity.User;
import com.huidao.util.JDBCUtil;


public class OrderServiceImpl implements OrderService{
	int pageSize = 5;
	OrderDao dao = new OrderDaoImpl();
	GoodsDao gDao = new GoodsDaoImpl();
	ShopDao sDao = new ShopDaoImpl();
	@Override
	public int addOrder(Order order,String sid) {
		Connection conn = null;
		try {
			conn =JDBCUtil.getConn();
			conn.setAutoCommit(false);
			//检验库存
			if(gDao.updateAccount(conn,order.getGoods().getGoodsId(), order.getGoodsNum())){
				//已经修改了库存
				if(dao.addOrder(conn,order)){
					if(sid==null){//判断是否是从购物车下单
						conn.commit();
						return 1;
					}else{
						if(sDao.delShop(conn, Long.parseLong(sid))){
							conn.commit();
							return 1;
						}else{
							conn.rollback();
							return 4;
						}
					}
				}else{
					conn.rollback();
					return 2;
				}
			}else{//库存不足
				conn.rollback();
				return 0;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return 3;
		}
		
	}
	@Override
	public boolean addOrderAll(long userId) {
		List<Shoppingcart> list = sDao.getAllList(userId);
		for(Shoppingcart s:list){
			Order order = new Order();
			order.setGoods(s.getGoods());
			order.setGoodsNum(s.getGoodsNum());
			User user = new User();
			user.setUserId(userId);
			order.setUser(user);
			addOrder(order,s.getShoppingcartId()+"");
		}
		return true;
	}
	@Override
	public List<Order> getOrderListByBuyer(int currentPage, long userId) {
		// TODO Auto-generated method stub
		return dao.getOrderByBuyer((currentPage-1)*pageSize, pageSize, userId);
	}
	@Override
	public int getTotalPageByBuyer(long userId) {
		int count = dao.getTotalCountByBuyer(userId);
		if(count%pageSize==0){
			return count/pageSize;
		}else{
			return count/pageSize+1;
		}
	}
	@Override
	public boolean updateOrderState(String id, String state) {
		return dao.updateOrderState(Long.parseLong(id), Integer.parseInt(state));
	}
	@Override
	public List<Order> getOrderListBySeller(int currentPage, long userId) {
		return dao.getOrderBySeller((currentPage-1)*pageSize, pageSize, userId);
	}
	@Override
	public int getTotalPageBySeller(long userId) {
		int count = dao.getTotalCountBySeller(userId);
		if(count%pageSize==0){
			return count/pageSize;
		}else{
			return count/pageSize+1;
		}
	}

}
